<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>
        购物车
      </caption>
      <thead>
        <tr>
          <th><input type="checkbox" v-model="isAll" /> <span>全选</span></th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in list" :key="index">
          <td>
            <input type="checkbox"  v-model="item.checked" />
          </td>
          <td>{{ item.name }}</td>
          <td>{{ item.price }}</td>
          <td>
            <button  @click="sub(item.name)" :disabled="item.num <= 1">-</button>
            <span>{{ item.num }}</span>
            <button  @click="add(item.name)">+</button>
          </td>
          <td>{{ item.price * item.num }}</td>
          <td><input type="button" value="删除" @click="del(item.name)" /></td>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">
            {{ totalPrice }}
          </td>
        </tr>
      </tfoot>
    </table>
  </div>
</template>

<script>
export default {
  props: {
    list: {
      required: true,
      type: Array,
    },
  },
  computed: {
    totalPrice() {
      return this.list.reduce((sum, item) =>{
        if (item.checked) {
          return  sum + item.price * item.num
        } else {
          return sum
        }
      }, 0);
    },
    isAll: {
      get() {
        return this.list.every((item) => item.checked);
      },
      set(value) {
        this.list.forEach((item) => (item.checked = value));
      },
    },
  },
  methods: {
    del(name) {
      this.$emit("del", name);
    },
    sub(name) {
      this.$emit("sub", name);
      console.log(name)
    },
    add(name) {
      this.$emit("add", name);
      console.log(name)
    },
  },
};
</script>

<style>
button {
  width: 16px;
  height: 16px;
  line-height: 16px;
  text-align: center;
  color: #000;
}
</style>